package solution._0110._0117;

import common.Node;

/**
 * Created by chen_snow
 * Date: 2021/6/29 22:25
 * Description: 填充每个节点的下一个右侧节点指针 II
 */
public class Solution {
    public Node connect(Node root) {
        doConnect(root);
        return root;
    }

    /**
     * 根据上一行的next，确定下一行的next
     * @param start
     */
    public void doConnect(Node start) {
        if (start == null) {
            return;
        }

        Node nextStart = null;
        Node current = null;

        while (start != null) {
            if (start.left != null) {
                if (nextStart == null) {
                    nextStart = start.left;
                }

                if (current != null) {
                    current.next = start.left;
                }
                current = start.left;
            }

            if (start.right != null) {
                if (nextStart == null) {
                    nextStart = start.right;
                }

                if (current != null) {
                    current.next = start.right;
                }
                current = start.right;
            }

            start = start.next;
        }
        doConnect(nextStart);
    }
}
